package com.group.eams.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.group.eams.mapper.RolePermissionMapper;
import com.group.eams.pojo.dto.RoleQueryDto;
import com.group.eams.pojo.dto.UpdateRolePermissionDto;
import com.group.eams.pojo.entity.Role;
import com.group.eams.pojo.entity.RolePermission;
import com.group.eams.pojo.vo.RoleListVo;
import com.group.eams.service.RoleService;
import com.group.eams.mapper.RoleMapper;


import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
* @author 恩哲欣
* @description 针对表【role(角色管理)】的数据库操作Service实现
* @createDate 2024-10-29 16:09:34
*/
@Service
@Slf4j
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role>
implements RoleService{
    @Autowired
    private RolePermissionMapper rolePermissionMapper;
    @Override
    public Page<RoleListVo> findRoleByWhere(Page<Role> page, RoleQueryDto roleQueryDto) {
        return getBaseMapper().findRoleByWhere(page,roleQueryDto);
    }

    @Override
    public void updateRolePermission(UpdateRolePermissionDto updateRolePermissionDto) {

        //1.删除角色对应的权限
        LambdaQueryWrapper<RolePermission> lambdaQueryWrapper=new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(RolePermission::getRoleId,updateRolePermissionDto.getRoleId());
        rolePermissionMapper.delete(lambdaQueryWrapper);

        //2.获取权限id集合
        List<Long> permissionIds = updateRolePermissionDto.getPermissionIds();
        if(CollectionUtil.isNotEmpty(permissionIds)){
            log.debug("往中间表插入数据...roleId:{},permissionId:{}",updateRolePermissionDto.getRoleId(),updateRolePermissionDto.getPermissionIds());

            permissionIds.forEach(permissionId ->{

                RolePermission rolePermission=new RolePermission();
                rolePermission.setRoleId(updateRolePermissionDto.getRoleId());
                rolePermission.setPermissionId(permissionId);
                rolePermissionMapper.insert(rolePermission);
            });
        }
    }
}
